<template>
  <div class="numInputs">
    <input
      v-for="(n, index) in amount"
      :key="n.index"
      v-model="arr[index]"
      maxlength="1"
      @keydown="nextFocus($event, index)"
      ref="numInput"
      type="tel"
    />
  </div>
</template>
<script>
export default {
  name: 'Input',
  props: {
    amount: {
      default: 4,
      type: Number
    }
  },
  data() {
    return {
      arr: []
    }
  },
  created() {
    setTimeout(() => {
      this.$refs.numInput[0] && this.$refs.numInput[0].focus()
    }, 0)
  },
  watch: {
    arr(val) {
      this.$emit('input', val.join(''))
    }
  },
  methods: {
    nextFocus($event, index) {
      // 键入时光标跳转
      this.arr[index] &&
        this.$refs.numInput[index + 1] &&
        this.$refs.numInput[index + 1].focus()
      // 删除
      if ($event.keyCode === 8) {
        if (this.arr[index]) {
          this.arr[index] = ''
          this.arr = JSON.parse(JSON.stringify(this.arr))
          this.$refs.numInput[index].focus()
        } else {
          this.$refs.numInput[index - 1] &&
            this.$refs.numInput[index - 1].focus()
        }
      }
    }
  }
}
</script>
<style lang="less">
.numInputs {
  display: flex;
  justify-content: space-evenly;
  margin: 25px 15px 10px 15px;
  input {
    width: 44px;
    height: 44px;
    border: 0.5px solid #ccc;
    font-size: 20px;
    text-align: center;
  }
}
</style>